package com.legrand.user.util;

import com.legrand.core.config.RedisUtils;
import com.legrand.core.entity.User;
import com.legrand.core.util.EncryptionUtil;
import com.legrand.core.util.StoreTime;
import com.legrand.user.dto.TokenDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.UUID;

/**
 * @author xiah
 * 2018-07-10 01:29:59
 * 该类主要用于生成accessToken和refreshToken  以及将用户信息存入redis
 */
@Component
public class TokenUtil {

    @Autowired
    private RedisUtils redisUtils;

    public TokenDTO getToken(User user) {
        String userId = user.getId().toString();
        if (redisUtils.exists(userId)) {
            Object object = redisUtils.get(userId);
            if (object != null) {
                String reToken = (String) object;
                if (reToken != null && !reToken.equals("")) {
                    String acToken = (String) redisUtils.get(reToken);
                    redisUtils.remove(reToken, acToken);
                }
            }
        }
        String accessToken = createToken();
        String refreshToken = createToken();
        /**md5加密方式存储token到redis*/
        Random random=new Random();
        if(random.nextInt(2)==1){
            redisUtils.set(EncryptionUtil.md5(accessToken), user, StoreTime.THREE_DAY);
            redisUtils.set(EncryptionUtil.md5(refreshToken), EncryptionUtil.md5(accessToken), StoreTime.THIRTY_DAY);
            redisUtils.set(userId, EncryptionUtil.md5(refreshToken), StoreTime.THIRTY_DAY);
            return new TokenDTO(accessToken, refreshToken,"1");
        }else{
            redisUtils.set(EncryptionUtil.sha1(accessToken), user, StoreTime.THREE_DAY);
            redisUtils.set(EncryptionUtil.sha1(refreshToken), EncryptionUtil.sha1(accessToken), StoreTime.THIRTY_DAY);
            redisUtils.set(userId, EncryptionUtil.sha1(refreshToken), StoreTime.THIRTY_DAY);
            return new TokenDTO(accessToken, refreshToken,"2");
        }

    }

    public String createToken() {
        return UUID.randomUUID().toString().toLowerCase();
    }
}
